package biz

import (
	"context"
	"time"

	"lianzi_gos/internal/mods/mpweixin/dal"
	"lianzi_gos/internal/mods/mpweixin/schema"
	"lianzi_gos/pkg/errors"
	"lianzi_gos/pkg/util"
)

// 意向客户表
type Buyer struct {
	Trans    *util.Trans
	BuyerDAL *dal.Buyer
}

// Query buyers from the data access object based on the provided parameters and options.
func (a *Buyer) Query(ctx context.Context, params schema.BuyerQueryParam) (*schema.BuyerQueryResult, error) {
	params.Pagination = false
	//如 2 不是管理员 就本人ID
	if params.Source != 2 {
		params.UID = util.FromUserID(ctx)
	}
	result, err := a.BuyerDAL.Query(ctx, params, schema.BuyerQueryOptions{
		QueryOptions: util.QueryOptions{
			OrderFields: []util.OrderByParam{
				{Field: "created_at", Direction: util.DESC},
			},
		},
	})
	if err != nil {
		return nil, err
	}
	return result, nil
}

// Get the specified buyer from the data access object.
func (a *Buyer) Get(ctx context.Context, id string) (*schema.Buyer, error) {
	buyer, err := a.BuyerDAL.Get(ctx, id)
	if err != nil {
		return nil, err
	} else if buyer == nil {
		return nil, errors.NotFound("", "Buyer not found")
	}
	return buyer, nil
}

// Create a new buyer in the data access object.
func (a *Buyer) Create(ctx context.Context, formItem *schema.BuyerForm) (*schema.Buyer, error) {
	buyer := &schema.Buyer{
		ID:        util.NewXID(),
		CreatedAt: time.Now(),
		UID:       util.FromUserID(ctx),
	}
	if err := formItem.FillTo(buyer); err != nil {
		return nil, err
	}

	err := a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.BuyerDAL.Create(ctx, buyer); err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return buyer, nil
}

// Update the specified buyer in the data access object.
func (a *Buyer) Update(ctx context.Context, id string, formItem *schema.BuyerForm) error {
	buyer, err := a.BuyerDAL.Get(ctx, id)
	if err != nil {
		return err
	} else if buyer == nil {
		return errors.NotFound("", "Buyer not found")
	}

	if err := formItem.FillTo(buyer); err != nil {
		return err
	}
	buyer.UpdatedAt = time.Now()

	return a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.BuyerDAL.Update(ctx, buyer); err != nil {
			return err
		}
		return nil
	})
}

// Delete the specified buyer from the data access object.
func (a *Buyer) Delete(ctx context.Context, id string) error {
	exists, err := a.BuyerDAL.Exists(ctx, id)
	if err != nil {
		return err
	} else if !exists {
		return errors.NotFound("", "Buyer not found")
	}

	return a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.BuyerDAL.Delete(ctx, id); err != nil {
			return err
		}
		return nil
	})
}
